import json
import os
import logging

# 创建日志记录器
def create_logger():
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s | 文件:%(filename)s,函数:%(funcName)s')
    return logging.getLogger(__name__)

# 加载语言数据
def load_language_data(logger):
    try:
        if os.path.exists('language.json') and os.path.getsize('language.json') > 0:
            with open('language.json', 'r') as f:
                language_data = json.load(f)
                logger.info("成功加载语言数据")
                return language_data
        else:
            logger.warning("语言数据文件不存在或为空")
            return {}
    except json.JSONDecodeError:
        logger.error("JSON 解析错误，无法解析文件")
        return {}
    except Exception as e:
        logger.error(f"加载语言数据时出现未知错误: {e}")
        return {}

# 写入语言数据
def write_language_data(logger, language_data, key, value):
    try:
        language_data[key] = value
        with open('language.json', 'w', encoding='utf-8') as f:
            json.dump(language_data, f, ensure_ascii=False, indent=4)
        logger.info(f"成功写入键 {key} 及其值到语言数据文件")
    except Exception as e:
        logger.error(f"写入语言数据时出现错误: {e}")


#################### 以下是载入代码 ####################
logger = create_logger()
language_data = load_language_data(logger)

# 示例写入操作
if language_data is not None:
    write_language_data(logger, language_data, "example_key", "example_value")

    